<template>
  <div>
    <canvas id="QRCode_header"></canvas>
    <el-input placeholder="请输入内容" v-model="copyData">
      <template slot="append">
        <el-button
          v-clipboard:copy="copyData"
          v-clipboard:success="onCopy"
          v-clipboard:error="onError"
        >复制</el-button>
      </template>
    </el-input>
    <el-button @click="downFile">下载</el-button>
  </div>
</template>

<script>
import QRCode from "qrcode" //引入生成二维码插件
export default {
  data() {
    return {
      QRCodeMsg: "",
      input2: "这是要复制的数据",
      copyData: ""
    }
  },
  mounted() {
    this.getQRCode()
  },
  methods: {
    getQRCode() {
      let opts = {
        errorCorrectionLevel: "H",//容错级别
        type: "image/png",//生成的二维码类型
        quality: 0.3,//二维码质量
        margin: 12,//二维码留白边距
        width: 200,//宽
        height: 180,//高
        // text: "http://www.xxx.com",//二维码内容
        color: {
          dark: "#333333",//前景色
          light: "#fff"//背景色
        }
      }
      this.QRCodeMsg = "http://www.qq.com" //生成的二维码为URL地址js
      let msg = document.getElementById("QRCode_header")
      // 将获取到的数据（val）画到msg（canvas）上
      QRCode.toCanvas(msg, this.QRCodeMsg, opts, function (error) {
        console.log(error)
      })
    },
    down(blob,name = "二维码") {
      console.log(blob.type)
      let type = blob.type.split("/")[1]
      let imgBlob = new Blob([blob],{type: blob.type})
      console.log(URL.createObjectURL(imgBlob))
      let body = document.body
      let src = URL.createObjectURL(imgBlob)
      let img = document.createElement("a")
      img.setAttribute("href", src)
      img.setAttribute("download",`${name}.${type}` )
      body.append(img)
      img.click()
      body.removeChild(img)
    },
    downFile() {
      let self = this
      let can = document.getElementById("QRCode_header")
      console.log(can)
      can.toBlob(res=>{
        console.log(res)
        self.down(res)
      })
    },
    onCopy(e) {
      console.log(e.text)
    },
    onError(e) {
      console.log(e.text)
    }
  }
}
</script>